<template>
  <div>
    <el-form
      ref="form"
      :model="dsForm"
      :rules="formRules"
      label-width="120px"
      label-position="left"
      size="small"
      class="ds-form"
    >
      <template v-if="openDataSource=='javascript'">
        <el-alert type="info" :closable="false" :title="eventName+'Hanlder(value){'" />
        <code-editor ref="ecEditor" v-model="dsForm.eventHandlerCode" :mode="'javascript'" :readonly="false" />
        <el-alert type="info" :closable="false" title="}" />
      </template>
      <template v-else>
        <el-row style="width: 100%">

          <el-col :span="20">
            <el-form-item label="唯一名称" prop="dataSource.uniqueName">
              <el-input v-model="dsForm.dataSource.uniqueName" /></el-form-item></el-col>
          <el-col :span="4">
            <el-form-item label-width="0" class="no-left-margin">
              <el-button style="width: 100%" plain @click="testDataSource">测试数据源</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="width: 100%">
          <el-col :span="20">
            <el-form-item label="请求地址" prop="dataSource.rUrl">
              <el-input v-model="dsForm.dataSource.rUrl" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="0" class="no-left-margin">
              <el-select v-model="dsForm.dataSource.rStyle">
                <el-option label="固定字符串" value="string" />
                <el-option label="变量表达式" value="variable" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="请求方式" prop="dataSource.rMethod">
          <el-radio-group v-model="dsForm.dataSource.rMethod">
            <el-radio-button label="get">get</el-radio-button>
            <el-radio-button label="post">post</el-radio-button>
            <el-radio-button label="put">put</el-radio-button>
            <el-radio-button label="delete">delete</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请求头">
          <el-row v-for="(rh, hIdx) in dsForm.dataSource.rHead" :key="hIdx" :gutter="8">
            <el-col :span="7">
              <el-form-item :prop="'dataSource.rHead.' + hIdx + '.name'" :rules="nameRules" label-width="0">
                <el-input v-model="rh.name" placeholder="名称" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :prop="'dataSource.rHead.' + hIdx + '.type'" label-width="0">
                <el-select v-model="rh.type">
                  <el-option label="字符串" value="String" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :prop="'dataSource.rHead.' + hIdx + '.value'" :rules="valueRules" label-width="0">
                <el-input v-model="rh.value" placeholder="值" />
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button icon="el-icon-delete" plain circle @click="deleteRequestHeader(hIdx)" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-button type="text" icon="el-icon-plus" @click="addRequestHeader">
                添加请求头</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="参数">
          <el-row v-for="(rp, pIdx) in dsForm.dataSource.rParam" :key="pIdx" class="rd-row" :gutter="8">
            <el-col :span="7">
              <el-form-item :prop="'dataSource.rParam.' + pIdx + '.name'" :rules="nameRules" label-width="0">
                <el-input v-model="rp.name" placeholder="名称" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item :prop="'dataSource.rParam.' + pIdx + '.type'" label-width="0">
                <el-select v-model="rp.type">
                  <el-option label="字符串" value="String" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :prop="'dataSource.rParam.' + pIdx + '.value'" :rules="valueRules" label-width="0">
                <el-input v-model="rp.value" placeholder="值" />
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button icon="el-icon-delete" plain circle @click="deleteRequestParam(pIdx)" />
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-button type="text" icon="el-icon-plus" @click="addRequestParam">
                添加请求参数</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-tabs v-model="activeName">
          <el-tab-pane label="成功处理" name="1">
            <el-alert type="info" :closable="false" title="(res) => {" />
            <code-editor ref="dhEditor" v-model="dsForm.dataSource.dataSuccess" :mode="'javascript'" :readonly="false" />
            <el-alert type="info" :closable="false" title="}" />
          </el-tab-pane>
          <el-tab-pane label="错误处理" name="2">
            <el-alert type="info" :closable="false" title="(error) => {" />
            <code-editor ref="ehEditor" v-model="dsForm.dataSource.dataError" :mode="'javascript'" :readonly="false" />
            <el-alert type="info" :closable="false" title="}" />
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-form>
    <el-dialog
      top="50px"
      title="测试数据源"
      :append-to-body="true"
      :visible.sync="showTestDataSourceDialogFlag"
      :show-close="false"
      custom-class="drag-dialog small-padding-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
    >
      <el-alert type="info" :closable="false" title="请求接口" />
      <code-editor v-model="dsvJson" :mode="'json'" :readonly="false" class="dsv-json-editor" />
      <div class="footer-button">
        <el-button type="primary" size="small" @click="doDataSourceRequest">执行请求</el-button>
        <el-button type="primary" size="small" plain @click="clearRequestResult">清空结果</el-button>
        <el-button size="small" @click="showTestDataSourceDialogFlag = false"> 取消</el-button>
      </div>
      <el-alert type="info" :closable="false" title="返回结果" />
      <code-editor ref="dsResultEditor" v-model="dsResultJson" :mode="'json'" :readonly="true" />
    </el-dialog>
  </div>
</template>

<script>
// import {  getCurrFields} from '@/api/system/desform/onlineForm/onlCgformHead'
import CodeEditor from '@/components/desform/online/codeEditor'
import { runDataSourceRequest } from '@/components/desform/online/onlineUtils'

export default {
  name: 'DataSourceForm',
   components: {
      CodeEditor
  },
  props: {
    openDataSource: {
      type: String,
      default: () => '',
      required: false
    },
    eventName: {
      type: String,
      default: () => '',
      required: false
    },
     data: {
      type: Object,
      default: () => {},
      required: false
    },
    dataFrom: {
      type: String,
      default: () => '',
      required: false
    }
  },
  data() {
    return {
      display: true,
      formOpen: false,
      title: undefined,
      showTestDataSourceDialogFlag: false, // 数据弹出层
      dsvJson: undefined,
      dsResultJson: undefined,
      dsForm: {
          openDataSource: this.openDataSource === 'javascript' ? 'N' : 'Y',
          eventType: this.eventName,
          eventHandlerCode: undefined,
          dataFrom: this.dataFrom,
          dataSource: {
                uniqueName: undefined,
                rUrl: undefined,
                rStyle: 'string',
                rHead: [],
                rParam: [],
                rMethod: 'get',
                dataSuccess: '  return res.data;',
                dataError: '  $message.error(error.msg);'
           },
           id: undefined
        },
      fieldsOption: [],
      activeName: '1',
      formRules: {
          'dataSource.uniqueName': [
            { required: true, trigger: ['blur', 'change'], message: '必填信息' }
          ],
          'dataSource.rUrl': [
            { required: true, trigger: ['blur', 'change'], message: '必填信息' }
          ],
          'dataSource.rMethod': [
            { required: true, trigger: ['blur', 'change'], message: '必填信息' }
          ]
        },
        nameRules: [
          { required: true, trigger: ['blur', 'change'], message: '必填信息' }
        ],
        valueRules: [
          { required: true, trigger: ['blur', 'change'], message: '必填信息' }
        ]
    }
  },
  computed: {
    guid() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random() * 16 | 0
        var v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
    }
  },
  watch: {
    data: {
      handler() {
         this.assignField(this.data)
      }
    }
  },
  created() {
    this.assignField(this.data)
  },
  methods: {
    deleteRequestHeader(idx) {
      this.dsForm.dataSource.rHead.splice(idx, 1)
    },
    addRequestHeader() {
      this.dsForm.dataSource.rHead.push({
        name: '',
        type: 'String',
        value: ''
      })
    },
    addRequestParam() {
      this.dsForm.dataSource.rParam.push({
        name: '',
        type: 'String',
        value: ''
      })
    },

    deleteRequestParam(idx) {
      this.dsForm.dataSource.rParam.splice(idx, 1)
    },
    assignField(data) {
      this.dsForm.id = data.id
      this.dsForm.eventHandlerCode = data.eventHandlerCode
      if (data.dataSource) {
          this.dsForm.dataSource.id = data.dataSource.id
          this.dsForm.dataSource.uniqueName = data.dataSource.uniqueName
          this.dsForm.dataSource.rUrl = data.dataSource.rUrl
          this.dsForm.dataSource.rStyle = data.dataSource.rStyle
          this.dsForm.dataSource.rMethod = data.dataSource.rMethod
          this.dsForm.dataSource.dataSuccess = data.dataSource.dataSuccess
          this.dsForm.dataSource.dataError = data.dataSource.dataError
          this.dsForm.dataSource.rHead = JSON.parse(data.dataSource.rHead)
          this.dsForm.dataSource.rParam = JSON.parse(data.dataSource.rParam)
          this.$forceUpdate()
      }
    },
    testDataSource() {
      const { uniqueName, rUrl, rHead, rParam } = this.dsForm.dataSource
      const globalDsv = { uniqueName, rUrl, rHead, rParam }
      this.dsvJson = JSON.stringify(globalDsv, null, '  ')
      this.showTestDataSourceDialogFlag = true
      // this.$refs.dsResultEditor.setValue('')
    },
    async doDataSourceRequest() { // 请求数据源
        const dsResult = await runDataSourceRequest(this.dsForm.dataSource, true, this.$message, this.formModel)
        this.$refs.dsResultEditor.setValue(JSON.stringify(dsResult, null, '  '))
    },
    clearRequestResult() { // 清空请求结果
       this.$refs.dsResultEditor.setValue('')
    }
  }
}
</script>

<style lang="scss" scoped>
.no-left-margin ::v-deep .el-form-item__content {
    margin-left: 0 !important;
  }
.rh-row, .rd-row {
  ::v-deep .el-col {
    margin: 5px 0;
  }
}
.ds-form {
  ::v-deep .el-form-item.is-required>.el-form-item__label:before {
    content: '' !important;
    margin-right: 0 !important;
  }

  ::v-deep .el-form-item.is-required>.el-form-item__label:after {
    content: '*' !important;
    font-weight: bold;
  }
}
.footer-button {
    float: right;
    margin-bottom: 12px;
  }
</style>
